package com.feicheng.service.a;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.task.Cache;
import com.feicheng.common.util.LocationUtils;
import com.feicheng.common.util.StringGenerator;
import com.feicheng.persistence.entity.*;
import com.feicheng.persistence.mapper.AmenjinMapper;
import com.feicheng.persistence.mapper.AroomMapper;
import com.feicheng.persistence.mapper.AstoreMapper;
import com.feicheng.persistence.service.*;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class FMdService {

    @Autowired
    IAstoreService storeService;

    @Autowired
    IAroomService roomService;

    @Autowired
    IAmountService iAmountService;

    @Autowired
    IAdzService dzService;

    @Autowired
    IAzjService zjService;

    @Autowired
    IAmenjinService menjinService;

    @Autowired
    IAkechengitemService akechengitemService;

    @Autowired
    IAkechengService akechengService;

    @Autowired
    IAjiaolianService ajiaolianService;

    @Autowired
    IClientService clientService;

    @Autowired
    IAroomyyjlService yyjlService;

    @Autowired
    LocationUtils locationUtils;

    @Autowired
    Cache cache;

    private JSONObject initClient() {
        Asetting asetting = cache.getObject("Asetting", Asetting.class);
        String openId = StringGenerator.getID("OPENID");
        JSONObject result = new JSONObject();
        Client client = new Client();
        client.setOpenid(openId);
        client.setAppid(asetting.getDappid());
        client.setClientid(StringGenerator.getID("CLI"));
        client.setHeadimg("https://wimg.588ku.com/gif620/21/04/25/26c111bdfb2b4c9e872d83f530a86e4b.gif");
        clientService.save(client);

        Amount amount = new Amount();
        amount.setAmount(0);
        amount.setOpenid(openId);
        iAmountService.save(amount);

        result.put("client", client);
        result.put("amount", amount);

        Adz adz = new Adz();
        adz.setDzid(StringGenerator.getID("DZ"));
        adz.setOpenid(openId);
        adz.setCover("https://wimg.588ku.com/gif620/20/09/11/1e6354a487be8ff16f8495542c14f980.gif");
        adz.setClientid(client.getClientid());
        dzService.save(adz);
        result.put("adz", adz);

        return result;
    }

    public JSONObject importMd(JSONObject param) {
        JSONObject mds = cache.getJSONObject("mdsname");
        JSONArray asr = param.getJSONArray("mds");
        int total = asr.size();
        param.put("total", total);
        int error = 0;
        int success = 0;
        for (int index = 0; index < asr.size(); index++) {
            JSONObject ar = asr.getJSONObject(index);
            String sname = ar.getString("sname");
            if (mds.containsKey(sname)) {
                error++;
                continue;
            }
            String sheng = ar.getString("sheng");
            String shi = ar.getString("shi");
            String qu = ar.getString("qu");
            String address = ar.getString("address");
            String imgs = ar.getString("imgs");
            String cover = ar.getString("cover");

            try {
                Astore md = new Astore();
                md.setStoreid(StringGenerator.getID("JMD"));
                md.setSname(sname+"-共享课房");
                JSONObject location = locationUtils.getJWD(sheng+shi+qu+address);
                JSONObject jwd = location.getJSONObject("location");
                md.setJd(jwd.getDouble("lng"));
                md.setWd(jwd.getDouble("lat"));
                md.setPcode(locationUtils.getCnCode(sheng));
                md.setScode(locationUtils.getCnCode(shi));
                md.setQcode(locationUtils.getCnCode(qu));
                md.setCover(cover);
                JSONArray imgar = new JSONArray();
                if (StringUtils.hasLength(imgs)) {
                    String[] imga = imgs.split(",");
                    for (String s : imga) {
                        imgar.add(s);
                    }
                }
                md.setImgs(imgar);
                md.setStu("T");
                md.setFlg(true);
                md.setBj("k");
                md.setYys(true);
                md.setCs(true);
                md.setKt(true);
                md.setGys(true);
                md.setWifi(true);
                md.setLy(true);
                JSONObject clientObj = this.initClient();
                Adz adz = clientObj.getObject("adz", Adz.class);
                md.setDzid(adz.getDzid());
                storeService.save(md);
                ar.put("mdid", md.getStoreid());
                success++;
            } catch (Exception e) {
                error++;
                continue;
            }

        }
        param.put("success", success);
        param.put("error", error);
        return param;
    }

    public JSONObject getFjmd(JSONObject param) {
        Integer radius = param.getInteger("radius");
        String jd = param.getString("jd");
        String wd = param.getString("wd");
        AstoreMapper astoreMapper = (AstoreMapper) storeService.getBaseMapper();
        List<JSONObject> mds = astoreMapper.getFjStores(radius, jd, wd);
        param.put("mds", mds);
        return param;
    }

    /**
     * 修改门店 霞姐
     * @param param
     * @return
     */
    public JSONObject open(JSONObject param) {
        String mdid = param.getString("mdid");
        Astore astore = storeService.getById(mdid);
        Adz adz = dzService.getById(astore.getDzid());
        Client client = clientService.getById(adz.getClientid());

        if (client.getYj() == 0) {
            throw new SystemException("请先缴纳保证金");
        }

        if (!StringUtils.hasLength(adz.getTx())) {
            throw new SystemException("请先设置人脸");
        }

        // 检查房间数量

        // 检查门禁数量

        astore.setFlg(true);
        storeService.updateById(astore);
        param.put("astore", astore);
        return param;
    }

    public JSONObject close(JSONObject param) {
        String mdid = param.getString("mdid");
        Astore astore = storeService.getById(mdid);
        astore.setFlg(false);
        storeService.updateById(astore);
        param.put("astore", astore);
        return param;
    }


    /**
     * 门店分页查询  霞姐
     * @param param
     * @return
     */
    public JSONObject getMdByPage(JSONObject param) {
        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (null == current || current < 0) {
            current = 1;
        }

        if (null == size || size < 0) {
            size = 16;
        }

        IPage<JSONObject> page = new Page<JSONObject>(current, size);

        QueryWrapper<JSONObject> qw = new QueryWrapper<>();
        String sname = param.getString("sname");
        if (StringUtils.hasLength(sname)) {
            qw.like("astore.sname", sname);
        }

        String dzid = param.getString("dzid");
        if (StringUtils.hasLength(dzid)) {
            qw.like("astore.dzid", dzid);
        }

        Boolean flg = param.getBoolean("flg");
        if (null != flg) {
            qw.eq("astore.flg", flg);
        }

        String zjid = param.getString("zjid");
        if (StringUtils.hasLength(zjid)) {
            qw.eq("astore.zjid", zjid);
        }

        String zjgsid = param.getString("zjgsid");
        if (StringUtils.hasLength(zjgsid)) {
            qw.eq("astore.zjgsid", zjgsid);
        }

        String jd = param.getString("jd");
        String wd = param.getString("wd");

        AstoreMapper astoreMapper = (AstoreMapper) storeService.getBaseMapper();
        page = astoreMapper.getStoreWithDzByPage(page, qw, jd, wd);
        param.put("astores", page);
        return param;

    }

    /**
     * 门店全查询 霞姐
     * @param param
     * @return
     */
    public JSONObject getMds(JSONObject param) {
        QueryWrapper<Astore> qw = new QueryWrapper<>();
        String sname = param.getString("sname");
        if (StringUtils.hasLength(sname)) {
            qw.like("sname", sname);
        }
        Boolean flg = param.getBoolean("flg");
        if (null != flg) {
            qw.eq("flg", flg);
        }
        param.put("astores", storeService.list(qw));
        return param;
    }

    /**
     * 门店新增  霞姐
     * @param param
     * @return
     */
    public JSONObject newMd(JSONObject param) {
        // 获取门店信息对象
        Astore astore = param.getObject("astore", Astore.class);
        if (!StringUtils.hasLength(astore.getSname())) {
            throw new SystemException("门店名必须录入");
        }
        // 生成门店id
        if (!StringUtils.hasLength(astore.getStoreid())) {
            astore.setStoreid(StringGenerator.getID("MD"));
        }
        astore.setAkey(StringGenerator.generate(6)); //待设置

        astore.setFlg(false); //开店状态
        String dzid = astore.getDzid();
        Adz adz = dzService.getById(dzid);
        Client client = clientService.getById(adz.getClientid());

        if (StringUtils.hasLength(client.getFromid())) {
            QueryWrapper<Azj> azjqw = new QueryWrapper<>();
            azjqw.eq("clientid", client.getFromid());
            try {
                Azj azj = zjService.getOne(azjqw, true);
                if (null != azj) {
                    astore.setZjid(azj.getZjid());
                    astore.setZjgsid(azj.getZjgsid());
                }

            } catch (TooManyResultsException e) {

            }
        }
        storeService.save(astore);
        param.put("astore", astore);
        return param;
    }


    /**
     * 修改门店 霞姐
     * @param param
     * @return
     */
    public JSONObject updateMd(JSONObject param) {
        Astore astore = param.getObject("astore", Astore.class);
        storeService.updateById(astore);
        astore = storeService.getById(astore.getStoreid());
        param.put("astore", astore);
        return param;
    }

    /**
     * 修改门店 霞姐
     * @param param
     * @return
     */
    public JSONObject removeMd(JSONObject param) {
        Astore astore = param.getObject("astore", Astore.class);
        astore = storeService.getById(astore.getStoreid());
        storeService.removeById(astore.getStoreid());
        return param;
    }

    /**
     * 门店详细查询 雷哥
     * @param param
     * @return
     */
    public JSONObject getMd(JSONObject param) {

        String storeid = param.getString("storeid");
        if (!StringUtils.hasLength(storeid)) {
            throw new SystemException("门店id必须指定");
        }
        // 门店信息
        Astore astore = storeService.getById(storeid);
        param.put("astore", astore);

        Adz adz = dzService.getById(astore.getDzid());
        param.put("adz", adz);

        // 房间信息
        QueryWrapper<Aroom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("storeid", astore.getStoreid());

        String jyms = param.getString("jyms");
        if (StringUtils.hasLength(jyms)) {
            queryWrapper.eq("jyms", jyms);
        }

        AroomMapper aroomMapper = (AroomMapper) roomService.getBaseMapper();
        List<Aroom> rooms = aroomMapper.selectList(queryWrapper);
        param.put("rooms", rooms);

        //门禁信息
        QueryWrapper<Amenjin> qw = new QueryWrapper<>();
        qw.eq("storeid", astore.getStoreid());
        qw.isNull("roomid").or(wrapper -> wrapper.eq("roomid", ""));
        AmenjinMapper amenjinMapper = (AmenjinMapper) menjinService.getBaseMapper();
        List<Amenjin> menjins = amenjinMapper.selectList(qw);
        param.put("menjins", menjins);

        //根据课程item查询课程信息
        QueryWrapper<Akechengitem> kcItemqw = new QueryWrapper<>();
        kcItemqw.select("DISTINCT kcid").eq("storeid", storeid);

        JSONArray kcids = new JSONArray();
        akechengitemService.getBaseMapper().selectList(kcItemqw, item -> {
            kcids.add(item.getResultObject().getKcid());
        });

        QueryWrapper<Akecheng> kcqw = new QueryWrapper<>();
        if (!kcids.isEmpty()) {
            kcqw.in("kcid", kcids);
            List<Akecheng> kechengs = akechengService.list(kcqw);
            param.put("kechengs", kechengs);
        }

        //根据课程表查询教练信息
        JSONArray jlids = new JSONArray();
        akechengService.getBaseMapper().selectList(kcqw, item -> {
            jlids.add(item.getResultObject().getJlid());
        });
        QueryWrapper<Ajiaolian> jlqw = new QueryWrapper<>();
        if (!jlids.isEmpty()) {
            jlqw.in("jlid", jlids);
            List<Ajiaolian> jiaolians = ajiaolianService.list(jlqw);
            param.put("jiaolians", jiaolians);
        }

        return param;

    }

    /**
     * 门店盈利查询 zhoujunying
     * @param
     * @return
     */
    public JSONObject getMdsWithAmont() {
        JSONObject param = new JSONObject();
        AstoreMapper astoreMapper = (AstoreMapper) storeService.getBaseMapper();
        List<JSONObject> mdsWithAmont = astoreMapper.getMdsWithAmont();
        param.put("mdsWithAmont", mdsWithAmont);
        return param;
    }
}


